package lv.accenture.ex11;

public class Hilbert {
public static String sampleSVG(int order, String color, String fill) {
    	
    	int size = (int) Math.pow(2, order);
    	
       	StringBuffer buf = new StringBuffer();

       	buf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
       	buf.append("<!-- Generator: Adobe Illustrator 12.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 51448)  -->\n");
       	buf.append("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\" [\n");       	
       	buf.append("<!ENTITY ns_svg \"http://www.w3.org/2000/svg\">\n");
       	buf.append("<!ENTITY ns_xlink \"http://www.w3.org/1999/xlink\">\n");
		buf.append("]>\n");
		buf.append("<svg version=\"1.1\" id=\"Layer_1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"20cm\" height=\"20cm\" viewBox=\"0 0 " + size + " " + size + "\" overflow=\"visible\" enable-background=\"new 72.5 -0.599 232.649 142.086\" xml:space=\"preserve\">\n");
        buf.append("<title>Hilbert curve</title>\n");
        buf.append("<desc>This is a sample SVG file for Hilbert curve</desc>\n");
        buf.append("<rect x=\"0\" y=\"0\" width=\"" + size + "\" height=\"" + size + "\" fill=\"#fdfdfd\"/>\n");
        buf.append("<g id=\"admboundaries\" transform=\"translate(0," + size + ") scale(1 -1)\" style=\"stroke:black;stroke-width:0.1;\">\n");
        buf.append("<rect x=\"0\" y=\"0\" width=\"" + size + "\" height=\"" + size + "\" fill=\"" + fill + "\"/>\n");
        buf.append("<path fill=\"" + color + "\" stoke=\"black\" d=\"" + hilbertSVG(order) + "\"/>\n");
        buf.append("</g>\n");
        buf.append("</svg>\n");
        
        return buf.toString();
	}
  
    // object rotation method
    public static String rotate(String S, String side){
    	String[] sa = new String[]{"h1","h-1","v1","v-1"};
    	String[] sa2 = null;
    	
    	if(side=="right"){    		
        	sa2 = new String[]{"V1","V-1","H1","H-1"};
    	}
    	else if(side=="left"){    		
        	sa2 = new String[]{"V-1","V1","H-1","H1"};
    	}
    	
     	for(int i=0; i<sa.length; i++){
    		S = S.replaceAll(sa[i], sa2[i]);
    	}	
     	
     	S = S.toLowerCase();    
    	
    	return S;
    }

     
	public static String hilbertSVG(int order) {
		String begin  = new String("v1 h1 v-1");		
		   	for (int i=1; i < order; i++) {		
				    			
			begin = rotate(begin, "right") + " v1 " + begin + " h1 " + begin + " v-1 " + rotate(begin, "left");
		}
		return "M 0.5 0.5 " + begin;
	}
}
